<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>在线聊天</title>
    <link rel="stylesheet" href="css/detail.css">
    <script src="http://47.106.66.89:8080/js/vue.min.js"></script>
    <script src="http://47.106.66.89:8080/js/axios.min.js"></script>
    <link href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css" rel="stylesheet">
    <script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
    <script src="js/myhead.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link rel="stylesheet" href="css/reset.css">
    <style>
        .comment { width: 680px; margin: 20px auto; position: relative; background: #fff; padding: 20px 50px 50px; border: 1px solid #DDD; border-radius: 5px; }
        .comment h3 { height: 28px; line-height: 28px }
        .com_form { width: 100%; position: relative }
        .input { width: 99%; height: 60px; border: 1px solid #ccc }
        .com_form p { height: 28px; line-height: 28px; position: relative; margin-top: 10px; }
        span.emotion { width: 42px; height: 20px; padding-left: 20px; cursor: pointer }
        span.emotion:hover { background-position: 2px -28px }
        .qqFace { margin-top: 4px; background: #fff; padding: 2px; border: 1px #dfe6f6 solid; }
        .qqFace table{background-color: #FFFFFF}
        .qqFace table td { padding: 0px; }
        .qqFace table td img { cursor: pointer; border: 1px #fff solid; }
        .qqFace table td img:hover { border: 1px #0066cc solid; }
        #show { width: 770px; margin: 20px auto; background: #fff; padding: 5px; border: 1px solid #DDD; vertical-align: top; }
        .sub_btn { position: absolute; right: 0px; top: 0; display: inline-block; zoom: 1; /* zoom and *display = ie7 hack for display:inline-block */  *display: inline;
            vertical-align: baseline; margin: 0 2px; outline: none; cursor: pointer; text-align: center; font: 14px/100% Arial, Helvetica, sans-serif; padding: .5em 2em .55em; text-shadow: 0 1px 1px rgba(0,0,0,.6); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2); box-shadow: 0 1px 2px rgba(0,0,0,.2); color: #e8f0de; border: solid 1px #538312; background: #64991e; background: -webkit-gradient(linear, left top, left bottom, from(#7db72f), to(#4e7d0e)); background: -moz-linear-gradient(top, #7db72f, #4e7d0e);  filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#7db72f', endColorstr='#4e7d0e');
        }
        .sub_btn:hover { background: #538018; background: -webkit-gradient(linear, left top, left bottom, from(#6b9d28), to(#436b0c)); background: -moz-linear-gradient(top, #6b9d28, #436b0c);  filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#6b9d28', endColorstr='#436b0c');
        }
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            margin-left: -710px;
            margin-top: 15px;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 30px;
            height: 17px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<div id="app" style="height: 100%">
    <myhead @uo="getUserinfo">
        <template #nologined>
            <a href="login.html">登录</a>
            <el-link type="primary">注册</el-link>
        </template>
        <template #logined="props">
            <el-avatar :size="50" :src="props.userinfo.photo"></el-avatar>
        </template>
    </myhead>
    <div class="chatName" style="width: 900px;text-align:center;line-height:40px;height: 40px;margin: 0px auto;font-size: 20px">正在和 {{sendUser.uname}} 聊天</div>
    <main class="m900 flexbtw" style="height: calc(87% - 75px)">
        <article>
      <div style="min-height: 600px;overflow: auto">
          <div class="msgs" v-if="getChat.length>0">
              <div  :class={recv:userinfo.usid!=item.usid,send:userinfo.usid==item.usid,}  v-for="item in getChat">
                  <el-avatar style="margin: 0px 10px" :size="50" :src="item.userinfo.photo"></el-avatar>
                 <div>
                     <img style="max-width: 200px;max-height: 100px;object-fit: cover" v-if="item.content.indexOf('file:'==0)" :src="item.content.substring(5)" alt="">
                     <span v-if="item.content.startsWith('file')==false&&item.content.startsWith('[')==false" style ="line-height: 60px;margin:0px 10px" class="msg">{{item.content}}</span>
                     <span  v-if="item.content.startsWith('[')==true" style="max-width: 200px;max-height: 100px;object-fit: cover;line-height: 50px" v-html="replace_em(item.content)"></span>
                 </div>
              </div>
          </div>
          <div v-else></div>
          <div class="msgs" v-if="zu.length>0">
              <div :class={recv:userinfo.uname!=item.fromName,send:userinfo.uname==item.fromName,}  v-for="item in zu">
                  <el-avatar style="margin: 0px 10px" v-if="userinfo.uname==item.fromName" :size="50" :src="userinfo.photo"></el-avatar>
                  <el-avatar style="margin: 0px 10px" v-else :size="50" :src="sendUser.photo"></el-avatar>

                 <div>
                     <img v-if="item.message.indexOf('file:'==0)" style="max-width: 200px;max-height: 100px;object-fit: cover"  :src="item.message.substring(5)" alt="">
                     <span  v-if="item.message.startsWith('[')==true" style="max-width: 200px;max-height: 100px;object-fit: cover;line-height: 50px" v-html="replace_em(item.message)"></span>
                     <span v-if="item.message.startsWith('file')==false&&item.message.startsWith('[')==false"  style="line-height: 60px;margin:0px 10px" class="msg">{{item.message}}</span>
                 </div>
              </div>
          </div>
          <div v-else></div>
      </div>
            <textarea  v-model="chat.content" @paste="sendImage" class="input"  id="saytext" name="saytext"></textarea>

            <!--
                        <textarea name="saytext" placeholder="请输入内容..." id="msg saytext" v-model="chat.content" @paste="sendImage"></textarea>
            -->
            <div id="ops">
                <span style="margin-top:20px;float: left;width: 50px;height: 100%;display: inline-block;" class="emotion" @click="showEmotion">表情</span>
                <el-upload
                        class="avatar-uploader"
                        action="other/common/uploads"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
               <button @click="send">发送</button>
            </div>
        </article>
    </main>
    <div class="footer" style="margin-top: 10px">
        <div class="er"></div>
        <div class="newBlog">
            <p style="margin-top: 60px;font-size: 18px;font-weight: bold">最近博客</p>
            <p style="margin-top: 10px">用户故事(User Strory)</p>
            <p style="margin-top: 10px"> 关于刻意联系的清单</p>
            <p style="margin-top: 10px">失败要趁早</p>
        </div>
        <div class="lian">
            <p style="margin-top: 60px;font-size: 18px;font-weight: bold">联系我们</p>
            <p style="margin-top: 10px">Email：2435939131@qq.com</p>
            <p style="margin-top: 10px">QQ：2435939131</p>
        </div>
        <div class="lie">
            <p style="margin-top: 60px;font-size: 18px;font-weight: bold">Lirenmi</p>
            <p style="margin-top: 10px">这是我的个人博客、会分享关于编程、写作、思考相关的任何</p>
            <p style="margin-top: 10px">内容，希望可以给来到这儿的人有所帮助...</p>
        </div>
    </div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.qqFace.js"></script>
<script>
    let app=new Vue({
        el:"#app",
        data:{
            ws:null,
            userinfo:"",
            chat:{content:'',usid:'',uid:'',status:1},
            zu:[],
            messa:{
                fromName:'',
                message:'',
                system:false
            },
            getChat:[],
            sendUser:'',


            lockRecontent:false,  //是否真正建立连接
            timeOut:60*1000,  //60秒一次
            timeoutObj:undefined, //时间间隔对象
            serverTimeoutObj:undefined,
            timeOutNum:undefined,


            saytext: '',
            show: '',
            imageUrl: '',
        },
        methods:{
            handleAvatarSuccess(response) {
                if(response.code==1){
                    this.chat.content="file:"+response.data
                    this.ws.send(JSON.stringify(this.chat));
                    this.insertChat();
                }
              // console.log(response);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },



            submit() {
                var saytext = document.getElementById("saytext").value;
                console.log(saytext);
                this.show = this.replace_em(saytext);
            },
            showEmotion() {
                $('#facebox').toggle();
            },
            replace_em(str) {
                console.log(str)
                str = str.replace(/\</g, '<');
                str = str.replace(/\>/g, '>');
                str = str.replace(/\n/g, '<br/>');
                str = str.replace(/\[em_([0-9]*)\]/g, '<img src="arclist/$1.gif" />');
                return str;
            },



            Connection(){
                    this.ws=new WebSocket("ws://localhost:5000/chat/"+this.userinfo.usid);
                    this.ws.onopen=()=>{
                        console.log("服务器连接成功");
                        //开启心跳
                        this.start();
                    };
                    this.ws.onclose=()=>{
                        console.log("服务器已断开")
                        this.reconnect();
                    };
                    this.ws.onerror=()=>{
                        this.reconnect();
                    }
                    this.ws.onmessage=(data)=>{
                        console.log(data)
                        if(JSON.parse(data.data).system==false){
                           this.zu.push(JSON.parse(data.data))
                            this.chat.content="";

                        }
                    }
            },
            getUserinfo(userinfo){
                this.userinfo=userinfo;
                this.Connection();
                this.selectChat();
                this.selectByUid();
            },
            sendImage(e){
                var clipboard = e.clipboardData;
                if (clipboard.items[0].type.match(/image/)) {
                    let fd = new FormData();
                    let blob = clipboard.items[0].getAsFile();
                    let nm = "image.jpg"
                    fd.append("file",blob,nm);
                    axios.post("other/common/upload",fd).then(res=>{
                        console.log(res.data)
                        if(res.data.code==1){
                            this.chat.content="file:"+res.data.data
                            this.ws.send(JSON.stringify(this.chat));
                            this.insertChat();
                        }
                    });
                }
            },
            //点击发送
            send(){
                if(this.chat.content==''||this.chat.content==null){
                    var saytext = document.getElementById("saytext").value;
                    if(saytext==''||saytext==null){
                        alert("请先输入内容，在进行发送");
                    }else{
                        this.chat.content=saytext;
                        this.ws.send(JSON.stringify(this.chat));
                        this.insertChat();
                    }

                }else{
                  this.ws.send(JSON.stringify(this.chat));
                    this.insertChat();
                }
            },
            //查询聊天记录
            selectChat(){
                this.chat.usid=this.userinfo.usid;
                this.chat.uid=location.search.replace("?","");
                this.chat.status=Number(this.chat.usid)+Number(this.chat.uid);
                axios.post("other/chat/selectChat",this.chat).then(res=>{
                 this.getChat=(res.data);
                 console.log(this.getChat);
                })
            },
            //查找被发消息人的信息
            selectByUid(){
              axios.get("user/userinfo/selectByUid?usid="+this.chat.uid).then(res=>{
                 this.sendUser=(res.data.data);

              })
            },
            //将聊天记录存到数据库
            insertChat(){
                axios.post("other/chat/insertChat",this.chat).then(res=>{
                    console.log(res.data);
                })
            },



            start(){
                this.timeoutObj&&clearTimeout(this.timeoutObj);
                this.serverTimeoutObj&&clearTimeout(this.serverTimeoutObj)
              this.timeoutObj=setTimeout(()=>{
                    if(this.ws.readyState==1){
                        this.ws("heartCheck");
                    }else{
                        this.reconnect();
                    }
                    this.serverTimeoutObj=setTimeout(()=>{
                        this.ws.close();
                    },this.timeOut)
                },this.timeOut)
            },
            wsSend(msg){
                this.ws.send(msg);
            },
            reconnect(){
                if(this.lockRecontent){
                    return;
                }
                this.lockRecontent=true;
                this.timeOutNum&&clearTimeout(this.timeOutNum);
               this.timeOutNum=setTimeout(()=>{
                    this.Connection();
                    this.lockRecontent=false;
                },1000)
            },
            reset(){
                this.timeoutObj&&clearTimeout(this.timeoutObj);
                this.serverTimeoutObj&&clearTimeout(this.serverTimeoutObj)
                //重启心跳
                this.start();
            }

        },
        created(){

        },
        mounted() {
            this.$nextTick(() => {
                $('.emotion').qqFace({
                    id: 'facebox',
                    assign: 'saytext',
                    path: 'arclist/', //表情存放的路径
                });
            });
        },
    })
</script>
</body>
</html>



















































<style>
    * {
        padding: 0px;
        margin: 0px;
        font-family: "Arial", "Microsoft YaHei", "黑体", "宋体", sans-serif;
    }

    html,body{
        height: 100%;
    }
    body{
        display: flex;
        flex-direction: column;
    }

    a {
        text-decoration: none;
    }

    button{
        padding: 3px 10px;
    }

    .p900 {
        padding: 0px calc((100% - 900px) / 2);
    }

    .m900 {
        width: 900px;
        margin: 0px auto;
    }

    .flexbtw {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    header {
        background-color: #eee;
        flex: none;
    }
    header>h3{
        margin: 10px 0px;
    }

    main {
        flex: auto;
        background-color: #ddd;
    }

    footer {
        flex: none;
        padding: 5px;
        text-align: center;
        background-color: #eee;
    }

    aside {
        width: 200px;
        height: 100%;
        background-color: #ccc;
        flex: none;
    }

    article {
        height: 100%;
        flex: auto;
    }

    article {
        display: flex;
        flex-direction: column;
    }

    .msgs {
        box-sizing: border-box;
        min-height: 200px;
    }

    #msg {
        flex: none;
        width: 100%;
        height: 100px;
        box-sizing: border-box;
    }

    .send > * {
        float: right;
    }

    .recv > * {
        float: left;
    }

    .send, .recv {
        clear: both;
        padding: 5px 0px;
    }

    .user, .msg {
        padding: 5px;
    }

    .msg {
        background-color: #e9e9e9;
        border-radius: 3px;
    }

    aside>div{
        text-align: center;
        padding: 10px;
        margin: 3px;
        background-color:#8c939d;
    }

    aside>div:hover{
        background-color:#8c939d55;
        cursor: pointer;
    }

    #ops{
        text-align: right;
        padding: 7px;
    }
    #ops>*{
        box-sizing: border-box;
        height: 25px;
        vertical-align: middle;
        margin: 0px 5px;
        text-align: center;
    }
    textarea{
        padding: 3px;
    }
</style>